var express = require("express");
var router = express.Router();
const formidable = require("formidable");

/* GET home page. */
router.get("/", function(req, res, next) {
  res.render("index", { title: "Express" });
});

// 显示网页的表单
router.get("/portrait", (req, res) => {
  res.render("portrait");
});

// 处理文件上传
router.post("/portrait", (req, res, next) => {
  console.log("before Formidable");
  const form = formidable({
    multiples: true,
    uploadDir: __dirname + "/" + "../public/images/",
    keepExtensions: true,
  });
  console.log("after Formidable");

  form.parse(req, (err, fields, files) => {
    if (err) {
      next(err);
      return;
    }
    console.log(fields);
    console.log(files);
    // res.json({ fields, files });
    let url = "/images/" + files.portrait.newFilename;
    res.send(url);
  });
});

module.exports = router;
